﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;

namespace SnapObjects.Data
{
    internal class TemplateModelImportProvider<TModel> : ITemplateImportProvider
    {
        private readonly ICollection<TModel> _dataSource;

        private readonly IDictionary<string, Type> _columns;

        private readonly IModelFactory _factory;

        private readonly IModelAccessor _accessor;

        public TemplateModelImportProvider(ICollection<TModel> dataSource)
        {
            _dataSource = dataSource;

            _columns = new Dictionary<string, Type>();

            _factory = ModelFactoryFactory.Create(typeof(TModel));

            _accessor = _factory.GetAccessor();

            foreach (var item in _accessor.ModelMeta.Properties)
            {
                _columns.Add(item.Name, item.DataType);
            };
        }

        public IDictionary<string, Type> GetColumns()
        {
            return _columns;
        }

        public int Import(IEnumerable<IModelEntry> entries)
        {
            foreach (var entry in entries)
            {
                var model = _factory.Create();

                foreach (var item in entry.Properties)
                {
                    var value = entry.GetCurrentValue(item);

                    _accessor.SetValue(model, item, value);
                }

                _dataSource.Add((TModel)model);
            }

            return _dataSource.Count;
        }
    }
}
